package com.cloud.handler;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.cloud.bootstrap.BootstrapApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CustomPrepareEventLister
 * @Description: 自定义spring上下文准备完成事件监听器
 * @Version: v1.0.0
 * @Author: yangyuwei
 * @Date: 2022/5/25
 * Modification History:
 * Date             Author      Version     Description
 * -------------------------------------------------------------
 * 2022/5/25      yangyuwei      v1.0.0      创建
 */

public class CustomPrepareEventLister implements ApplicationListener<ApplicationPreparedEvent>, Ordered {
    private String dataId = "cloud-joyoung.yml";

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event) {
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        if(!applicationContext.isActive()){
            return;
        }
        //spring读取nacos配置中心配置文件的时机发生spring上下文开始事件中.
        //而nacos配置中心的javabean是在spring上下文准备完成事件中装配的,
        //如果想要额外的再读取一个配置中心的配置文件,
        //只要监听spring上下文准备完成事件,
        //获取到装配好的nacos的javabean,在javabean中增加相关配置项即可
        NacosConfigProperties.Config config = new NacosConfigProperties.Config();
        config.setDataId(dataId);
//        config.setGroup("DEFAULT_GROUP");//未设置命名空间时使用默认的命名空间
        NacosConfigProperties nacosConfigProperties = applicationContext.getBean("nacosConfigProperties",NacosConfigProperties.class);
        if(nacosConfigProperties!= null){
            if(nacosConfigProperties.getSharedConfigs()==null){
                List<NacosConfigProperties.Config> sharedConfigs = new ArrayList<>();
                sharedConfigs.add(config);
                nacosConfigProperties.setSharedConfigs(sharedConfigs);
            }else {
                Boolean match = nacosConfigProperties.getSharedConfigs().stream()
                        .anyMatch(nacosconfig->dataId.equals(nacosconfig.getDataId()));
                if(!match){
                    nacosConfigProperties.getSharedConfigs().add(config);
                }
            }
        }
    }


    @Override
    public int getOrder() {
        return BootstrapApplicationListener.DEFAULT_ORDER-1;
    }
}
